'use client'

import { useState, useEffect } from 'react'
import { useAuth } from '@/contexts/auth-context'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { LogOut, Smartphone, Monitor, Tablet, Globe } from 'lucide-react'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'

interface Session {
  id: string
  ip: string
  userAgent: string
  createdAt: string
  expiresAt: string
  isActive: boolean
  isCurrent: boolean
}

export function SessionManagement() {
  const { getUserSessions, terminateSession, terminateAllSessions } = useAuth()
  const [sessions, setSessions] = useState<Session[]>([])
  const [loading, setLoading] = useState(true)
  const [terminating, setTerminating] = useState<string | null>(null)
  const [terminatingAll, setTerminatingAll] = useState(false)

  const fetchSessions = async () => {
    setLoading(true)
    try {
      const sessionList = await getUserSessions()
      setSessions(sessionList)
    } catch (error) {
      console.error('获取会话列表失败:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchSessions()
  }, [])

  const handleTerminateSession = async (sessionId: string) => {
    setTerminating(sessionId)
    try {
      const success = await terminateSession(sessionId)
      if (success) {
        setSessions(sessions.filter(session => session.id !== sessionId))
      }
    } catch (error) {
      console.error('终止会话失败:', error)
    } finally {
      setTerminating(null)
    }
  }

  const handleTerminateAllSessions = async () => {
    setTerminatingAll(true)
    try {
      const count = await terminateAllSessions()
      // 重新获取会话列表
      await fetchSessions()
    } catch (error) {
      console.error('终止所有会话失败:', error)
    } finally {
      setTerminatingAll(false)
    }
  }

  const getDeviceIcon = (userAgent: string) => {
    if (!userAgent) return <Globe className="h-4 w-4" />
    
    if (userAgent.includes('Mobile') || userAgent.includes('Android') || userAgent.includes('iPhone')) {
      return <Smartphone className="h-4 w-4" />
    } else if (userAgent.includes('Tablet') || userAgent.includes('iPad')) {
      return <Tablet className="h-4 w-4" />
    } else {
      return <Monitor className="h-4 w-4" />
    }
  }

  if (loading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>登录设备管理</CardTitle>
          <CardDescription>管理您的登录会话</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center p-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>登录设备管理</CardTitle>
        <CardDescription>您可以在此查看和管理所有登录设备</CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        <Alert>
          <AlertDescription>
            这里显示了您账户的所有活跃登录会话。如果发现异常，请立即终止相关会话。
          </AlertDescription>
        </Alert>

        <div className="flex justify-end">
          <Button 
            variant="destructive" 
            onClick={handleTerminateAllSessions}
            disabled={terminatingAll}
          >
            {terminatingAll ? '处理中...' : '终止所有其他会话'}
          </Button>
        </div>

        <div className="space-y-4">
          {sessions.map((session) => (
            <div key={session.id} className="border rounded-lg p-4">
              <div className="flex items-start justify-between">
                <div className="flex items-start space-x-3">
                  <div className="mt-1">
                    {getDeviceIcon(session.userAgent)}
                  </div>
                  <div className="space-y-1">
                    <div className="flex items-center space-x-2">
                      <span className="font-medium">
                        {session.isCurrent ? '当前设备' : '其他设备'}
                      </span>
                      {session.isCurrent && (
                        <Badge variant="default">当前</Badge>
                      )}
                      {!session.isActive && (
                        <Badge variant="secondary">已终止</Badge>
                      )}
                    </div>
                    <p className="text-sm text-gray-500">
                      IP: {session.ip}
                    </p>
                    <p className="text-sm text-gray-500">
                      {session.userAgent}
                    </p>
                    <div className="text-xs text-gray-400 space-y-1">
                      <p>登录时间: {format(new Date(session.createdAt), 'yyyy年MM月dd日 HH:mm', { locale: zhCN })}</p>
                      <p>过期时间: {format(new Date(session.expiresAt), 'yyyy年MM月dd日 HH:mm', { locale: zhCN })}</p>
                    </div>
                  </div>
                </div>
                
                {!session.isCurrent && session.isActive && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleTerminateSession(session.id)}
                    disabled={terminating === session.id}
                  >
                    {terminating === session.id ? '终止中...' : '终止会话'}
                  </Button>
                )}
              </div>
            </div>
          ))}
        </div>

        {sessions.length === 0 && (
          <div className="text-center py-8 text-gray-500">
            暂无活跃会话
          </div>
        )}
      </CardContent>
    </Card>
  )
}